import re

from tppt.data.models import *

from tppt import importer

class UnknownDetailType(importer.Error):
	pass
class InvalidFormat(importer.Error):
	pass

def get_data(lines):
	data={}

	done=False

	if not lines[0]:
		#we skip empty lines
		lines_used=1
		done=True

	match_obj=re.compile('^(.*):$').match(lines[0])
	if not done and match_obj:
		key=str(match_obj.group(1))
		data[key]=lines[1]
		lines_used=2
		done=True

	match_obj=re.compile('^(.*)@$').match(lines[0])
	if not done and match_obj:
		key=str(match_obj.group(1))
		data[key]=lines[1:].join('\n')
		lines_used=len(lines)
		done=True
		
	if not done:
		raise InvalidFormat(lines[0])
	
	return data, lines_used

def set_entity_attr(entity, field_name, value):
	model=entity.__class__
	fields=model.get_fields_dict()
	field=fields[field_name]
	proc=importer.get_processor(field)
	setattr(entity, field_name, proc(value))

def import_result(data_string):
	lines=data_string.splitlines()

	data={}
	
	while lines:
		ndata, used = get_data(lines)
		data.update(ndata)
		lines=lines[used:]
	
	result=Result()
	
	result_fields=result.get_fields_dict().keys()
	
	proof=None
	details={}
	
	for key in data:
		if key in result_fields:
			set_entity_attr(result, key, data[key])
		elif key=='proof':
			proof=data[key]
		else:
			details[key]=data[key]
	
	result.save()
	
	if proof:
		prf_obj=Proof(origin=result, text=proof)
		prf_obj.save()
		
	for key in details:
		try:
			dt=ResultDetailType.objects.get(pk=key)
		except ResultDetailType.DoesNotExist:
			raise UnknownDetailType(key)
		rd=ResultDetail(detail_type=dt, result=result, value=details[key])
		rd.save()
